<template>
  <px-dialog v-model="visible" width="640px" @close="closeDrawer" @open="openDrawer">
    <template #header>
      <h3 style="font-weight: bold">{{ drawerType === "edit" ? "编辑" : "新增" }}品牌</h3>
    </template>
    <template #default>
      <px-form ref="formRef" prop="'name'" :model="formValue" :rules="rules" label-position="right" label-width="80px">
        <px-form-item label="品牌名称" prop="name">
          <px-input v-model="formValue.name" placeholder="请输入品牌名称" maxlength="50" clearable />
        </px-form-item>
      </px-form>
    </template>
    <template #footer>
      <px-button @click="closeDrawer">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </template>
  </px-dialog>
</template>
<script setup lang="ts">
import { saveSparePartBrand, updateSparePartBrand } from "@/api/equip/spareParts";
import { PxMessage } from "px-ui";
import { computed, ref, reactive, toRefs } from "vue";

// 调用父级-关闭抽屉、查询列表方法
const emits = defineEmits(["closeDrawer", "queryTable"]);

const formRef = ref();
const props = defineProps(["visible", "drawerType", "detailData"]);
const visible = computed(() => props.visible);

const state = reactive<any>({
  formValue: {}
});
const { formValue } = toRefs(state);

// 表单校验规则
const rules = computed(() => ({
  name: [
    {
      required: true,
      message: "品牌名称不能为空",
      trigger: ["blur", "change"]
    }
  ]
}));
const openDrawer = async () => {
  if (props.drawerType === "add") {
    formValue.value = {};
  } else {
    formValue.value = { ...props.detailData };
  }
};

// 关闭抽屉
const closeDrawer = () => {
  formRef.value.resetFields();
  emits("closeDrawer");
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(formValue.value));
      if (props.drawerType === "add") {
        await saveSparePartBrand(params);
        PxMessage.success("新增成功");
        emits("closeDrawer");
        emits("queryTable");
      } else {
        await updateSparePartBrand({ ...props.detailData, ...params });
        PxMessage.success("编辑成功");
        emits("closeDrawer");
        emits("queryTable");
      }
    }
  });
};
</script>
<style lang="scss" scoped>
:deep(.px-select) {
  width: 100%;
}
</style>
